﻿Imports System.IO
Imports System.Xml
Imports System.Xml.Serialization

Public Class FoodPlanList
    Inherits List(Of FoodPlanEntry)

    Public ReadOnly XmlPath As String = System.IO.Path.Combine(Application.StartupPath, "Data", "FoodPlanList_{0}.xml")

    ''' <summary>
    ''' Utility to convert a date into the expected format.
    ''' </summary>
    ''' <param name="dt">Date to convert</param>
    Private Function CreateDateString(ByVal dt As Date) As String
        Return dt.ToString("ddMMyyyy")
    End Function

    ''' <summary>
    ''' Loads the FoodPlanList for a given date
    ''' </summary>
    ''' <param name="dateString">date in ddmmyyyy format (or equivalent)</param>
    ''' <remarks></remarks>
    Public Sub LoadByDate(ByVal dateString As String)
        Dim actualPath As String = String.Format(XmlPath, dateString)
        Dim tempList As New List(Of FoodPlanEntry)

        If (File.Exists(actualPath)) Then

            Using reader As New StreamReader(actualPath)

                Dim serializer As New XmlSerializer(Me.GetType())
                tempList = CType(serializer.Deserialize(reader), FoodPlanList)
                reader.Close()
            End Using

            Me.Clear()
            Me.AddRange(tempList)

        End If
    End Sub
    ''' <summary>
    ''' Loads the FoodPlanList for a given date
    ''' </summary>
    ''' <param name="dt">date to load food plan for</param>
    ''' <remarks></remarks>
    Public Sub LoadByDate(ByVal dt As Date)
        LoadByDate(CreateDateString(dt))
    End Sub

    ''' <summary>
    ''' Saves the FoodPlan for a specific date
    ''' </summary>
    ''' <param name="dateString"></param>
    ''' <remarks></remarks>
    Public Sub SaveByDate(ByVal dateString As String)
        Dim actualPath As String = String.Format(XmlPath, dateString)

        Using writer As New StreamWriter(actualPath, False)

            Dim serializer As New XmlSerializer(Me.GetType())
            serializer.Serialize(writer, Me)

            writer.Flush()
            writer.Close()

        End Using
    End Sub

    ''' <summary>
    ''' Saves the FoodPlan against a specific date
    ''' </summary>
    ''' <param name="dt">Date to save the food plan against</param>
    ''' <remarks></remarks>
    Public Sub SaveByDate(ByVal dt As Date)
        SaveByDate(CreateDateString(dt))
    End Sub


End Class
